# 渠道策略管理
class Api::RegionStrategiesController < Api::BaseController
	before_filter :get_region
	before_filter :get_region_strategy, only: [:update, :destroy]

	# 渠道策略列表
	# 
	# Params
	# 	access_token: [String] authenication_token
	#   page: [Integer] 页码
	#   per: [Integer] 每页显示数
	# Return
	# 	status: [String] success
	#   list: [Hash] {{id, name, code, contact, phone, address}...}
	#   total: [Integer] 总数
	# Error
	#   status: [String] failed
	def index
		region_strategies = @region.region_strategies.page(params[:page]).per(params[:per])
		render json: {status: :success, list: region_strategies, total: region_strategies.total_count}
	end

	# 创建渠道策略
	#
	# Params
	# 	access_token: [String] authenication_token
	#   region_strategy[store_rate]: [String] 店长提成百分比
	# 	region_strategy[plan_rate]: [String] 企划提成百分比
	# Return
	# 	status: [String] success
	# 	msg: [String] 创建成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos
	def create
    region_strategy = RegionStrategy.new(region_strategy_params)

		if region_strategy.save!
			render json: {status: :success, msg: '创建成功'}
		else
			render json: {status: :failed, msg: region_strategy.errors.messages.values.first}
		end
	end

	# 创建渠道策略
	#
	# Params
	# 	access_token: [String] authenication_token
	#   region_strategy[store_rate]: [String] 店长提成百分比
	# 	region_strategy[plan_rate]: [String] 企划提成百分比
	# Return
	# 	status: [String] success
	# 	msg: [String] 创建成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos
	def update
		if @region_strategy.update_attributes(region_strategy_params)
			render json: {status: :success, msg: '更新成功'}
    else
    	render json: {status: :failed, msg: @region_strategy.errors.messages.values.first}
		end
	end

	def destroy
	end

	private

	def get_region
		@region = @account.regions.find(params[:region_id])
		raise 'not found' unless @region

		rescue => e
			render json: {status: :failed, msg: e.message}
	end

	def region_strategy_params
    params.permit(:store_rate, :plan_rate, :region_id, :store_id)
	end

	def get_region_strategy
		@region_strategy = @region.region_strategies.find(params[:id])
		raise 'not found' unless @region_strategy
		rescue => e
			render json: {status: :failed, msg: e.message}
	end

end
